﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpArgument;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.StorageHelper;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.Views
{
    public partial class ContentPage : PhoneApplicationPage
    {
        private WebViewPage navigatePopup;

        public ContentPage()
        {
            InitializeComponent();
            //
            AddHeaderToPivotItemInPivotMain();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //
            if (!(this.NavigationContext.QueryString != null && this.NavigationContext.QueryString.Count > 0))
            {
                MessageToastManager.Show("未获取到栏目信息！", Common.MessageToastLevel.Error);
                if (this.NavigationService.CanGoBack)
                    this.NavigationService.GoBack();
                return;
            }
            string channel = this.NavigationContext.QueryString["channel"];
            if (string.IsNullOrWhiteSpace(channel))
            {
                //TODO 获取参数为空
                MessageToastManager.Show("未获取到栏目信息！", Common.MessageToastLevel.Error);
                if (this.NavigationService.CanGoBack)
                    this.NavigationService.GoBack();
                return;
            }
            Channel item = JSONHelper.Deserialize<Channel>(channel);
            if (item == null)
            {
                MessageToastManager.Show("栏目信息丢失！", Common.MessageToastLevel.Error);
                if (this.NavigationService.CanGoBack)
                    this.NavigationService.GoBack();
                return;
            }

            //
            foreach (PivotItem pi in this.pivot.Items)
            {
                if (pi == null)
                    return;
                if (item.ChannelID.Equals((pi.Tag as Channel).ChannelID))
                {
                    this.pivot.SelectedItem = pi;
                    break;
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (this.navigatePopup != null)
            {
                this.navigatePopup.CloseWebViewPage();
                this.navigatePopup = null;
                e.Cancel = true;
            }
        }

        private void AddHeaderToPivotItemInPivotMain()
        {
            List<Channel> items = LoadDataFromCacheChannel();
            if (!(items != null && items.Count > 0))
            {
                return;
            }

            double fontSize = 50;
            Color foreground = CUWo.Common.Helper.HexToColor("#ff000000");
            Thickness margin = new Thickness(-10, -10, 0, 10);
            //

            foreach (Channel item in items)
            {
                if (item == null)
                    continue;
                if (string.IsNullOrWhiteSpace(item.ChannelID) || string.IsNullOrWhiteSpace(item.ChannelName))
                    continue;
                //
                PivotItem pi = new PivotItem();
                pi.Tag = item;
                pi.Header = new PivotItemHelper().CreateTextBlock(item.ChannelName, fontSize, foreground, margin);                   
                pi.ContentTemplate = this.llsDataTemplate;
                //
                this.pivot.Items.Add(pi);
            }
        }




        private List<Channel> LoadDataFromCacheChannel()
        {
            string cacheFilePath = string.Concat(Keys.ChinaUnicomeCacheDirectory, "/", typeof(Channel).Name);
            if (!IsolatedStorageHelper.Instance.FileExists(cacheFilePath))
            {
                LogHelper.LogInfo("数据文件不存在！");
                return null;
            }
            string content = IsolatedStorageHelper.Instance.ReadText(cacheFilePath);
            List<Channel> items = JSONHelper.Deserialize<List<Channel>>(content);
            if (!(items != null && items.Count > 0))
            {
                LogHelper.LogInfo("数据文件为空！");
                return null;
            }

            return items;
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PivotItem pi = this.pivot.SelectedItem as PivotItem;
            if (pi == null)
            {
                return;
            }
            Channel channel = pi.Tag as Channel;
            if (channel == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(channel.ChannelID) || string.IsNullOrWhiteSpace(channel.ChannelName))
            {
                return;
            }
            //
            LoadNewsContentToPivotItem(pi, channel);
        }

        /// <summary>
        /// 加载新闻内容至PivotItem
        /// </summary>
        /// <param name="pivotItem"></param>
        /// <param name="channel"></param>
        void LoadNewsContentToPivotItem(PivotItem pivotItem, Channel channel)
        {
            string mobileNumber = string.Empty;
            var romInfoString = IsolatedStorageHelper.Instance.ReadText(Keys.ROM_FILENAME);
            if (!string.IsNullOrWhiteSpace(romInfoString))
            {
                RomInfo romInfo = JSONHelper.Deserialize<RomInfo>(romInfoString);
                if (romInfo != null)
                {
                    mobileNumber = romInfo.Mobile;
                }
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.NewsContent().GetUrl(mobileNumber, channel.ChannelID, "0", 20, ArgsNewsContentMode.Front);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageNewsContent jsonResult = JSONHelper.Deserialize<JsonResultMessageNewsContent>(decryptStringResult);
                            if (jsonResult != null)
                            {
                                if (jsonResult.Msg != null)
                                {
                                    if (jsonResult.Msg.MessageErrors != null && jsonResult.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (jsonResult.Msg.MessageWarns != null && jsonResult.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (jsonResult.Msg.MessagePrompts != null && jsonResult.Msg.MessagePrompts.Count > 0)
                                        {
                                            BindDataToPage(pivotItem, jsonResult.NewsInf);
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

        void BindDataToPage(PivotItem pivotItem, IList<NewsInf> items)
        {
            if (!(items != null && items.Count > 0))
            {
                return;
            }

            var datasource = new ObservableCollection<NewsInf>(items);
            //this.llsTest.ItemsSource = datasource;
            LongListSelector lls = FindVisualChild<LongListSelector>(pivotItem);
            if (lls != null)
            {
                lls.ItemsSource = datasource;
            }


        }

        //查找可视化树某个类型的元素
        private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }


        void llsNewsContent_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var lls = (sender as LongListSelector);
            if (lls == null)
                return;
            NewsInf item = lls.SelectedItem as NewsInf;
            if (item == null)
                return;
            if (string.IsNullOrWhiteSpace(item.Lnk))
                return;

            this.navigatePopup = new WebViewPage(item.Lnk);
        }

    }
}